<template>
  <a-upload
    accept="image/jpeg"
    v-model:file-list="fileList"
    name="upload"
    list-type="picture-card"
    class="avatar-uploader"
    show-upload-list
    action="/api/upload"
    :max-count="1"
    :before-upload="beforeUpload"
    @change="handleChange"
    :headers="headers"
    @preview="handlePreview"
  >
    <div>
      <plus-outlined></plus-outlined>
      <div class="ant-upload-text">上传</div>
    </div>
  </a-upload>

  <a-modal
    :open="previewVisible"
    :title="previewTitle"
    :footer="null"
    @cancel="handleCancel"
  >
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>
<script setup>
import { ref } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons-vue";
import useUserStore from "@/store/user";
const emit = defineEmits(["changePic"]);
const props = defineProps(["initPic"]); // 外界给url
const fileList = ref([]);
console.log(props.initPic);

// 处理单个初始化数据 - 编辑进入时会有初始数据
// const handlerInitData = () => {
//   console.log(props.initPic);
//   // "public\\uploads\\3f17b53174d181e727e59cdcaea955621726194318906.jpg"
//   // {
//   //   uid: '',
//   //   name: 'image.png',
//   //   status: 'done',
//   //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
//   // },
// };

//watch无法监听初始化数据
import { handlerPicPath } from "@/utils/tools";

const refresh = (newV) => {
  console.log(newV);
  if (newV) {
    // 约束只能传一张图
    fileList.value = [
      {
        uid: -1,
        name: newV,
        status: "done",
        url: handlerPicPath(newV),
      },
    ];
  } else {
    fileList.value = [];
  }
};
// let flag = true;
// watch(
//   () => props.initPic,
//   (newV) => {
//     if (flag) {
//       fileList.value.push({
//         uid: -1,
//         name: newV,
//         status: "done",
//         url: handlerPicPath(newV),
//       });
//       flag = false;
//     }
//   }
// );

const userStore = useUserStore();
const headers = {
  Authorization: `Bearer ${userStore.token}`,
};

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

function getPreviewBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

let temp = [];
const loading = ref(false);
const imageUrl = ref("");
// 图片变化
const handleChange = (info) => {
  // console.log(info, fileList.value.length);
  // 因为beforeUpload为false 【限制2M和图片类型，不通过时虽然阻止ajax请求 但是读取本都文件为base64显示】
  // 继续验证
  if (fileList.value.length > 0) {
    const isJpgOrPng =
      fileList.value[0].type === "image/jpeg" ||
      fileList.value[0].type === "image/png";
    if (!isJpgOrPng) {
      fileList.value = temp;
      return;
    }
    // 防止不符合规则的替换当前图片
    const isLt2M = fileList.value[0].size / 1024 / 1024 < 2;
    if (!isLt2M) {
      fileList.value = temp;
      return;
    }
  } else {
    emit("changePic", "");
  }
  if (info.file.status === "uploading") {
    return;
  }
  if (info.file.status === "done") {
    // Get this url from response in real world.
    // 拿到当前文件的路径传递给外侧form，便于form继续处理
    console.log(info);
    emit("changePic", info.file.response.path);
    getBase64(info.file.originFileObj, (base64Url) => {
      loading.value = false;
    });
  }
  if (info.file.status === "error") {
    loading.value = false;
    message.error("upload error");
  }
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    console.log([...fileList.value]);
    temp = [...fileList.value];
    message.error("您只能上传JPG|PNG文件!");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    temp = [...fileList.value];
    message.error("图像必须小于2MB!");
    return false;
  }
  return true;
};
// 图片预览
const previewVisible = ref(false);
const previewImage = ref("");
const previewTitle = ref("");
// 取消弹框
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = "";
};
//处理语言
const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getPreviewBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
};
// defineExpose()  暴露数据  外界通过ref获取当前组件实例调用

defineExpose({ refresh });
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
